var cfg = require('cfg');

var socketOpen = false;
var socketMsgQueue = [];
var socketCallBack = function(res) {};

var sendSocketMessage = function (msg) {
  if (socketOpen) {
    wx.sendSocketMessage({
      data: msg
    })
  } else {
    socketMsgQueue.push(msg)
  }
}

var registCallBack = function(fun) {
  socketCallBack = fun;
}

var doCallBack = function() {
  socketCallBack();
}

var socketInit = function() {
  console.log('>>>>>>>socket well be init()');
  if (socketOpen) {
    return;
  }

  console.log('>>>>>>>socket now init()');
  wx.connectSocket({
    url: cfg.socketHost + '/webSocketServer?openId=' + wx.getStorageSync('loginUser').openId,
    data: {
    },
    method: "GET"
  })

  wx.onSocketOpen(function (res) {
    console.log('WebSocket连接已打开！');
    socketOpen = true
    for (var i = 0; i < socketMsgQueue.length; i++) {
      sendSocketMessage(socketMsgQueue[i])
    }
    socketMsgQueue = [];

    setInterval(function () {
      console.log('>>>>>send heart...');
      sendSocketMessage("ping");
    }, 15000);

  })

  wx.onSocketMessage(function(res) {
    if (res.data == 'pong') {
      console.log('>>>>>>socket message : ' + res.data);
    } else {
      let resoult = JSON.parse(res.data);
      console.log('>>>>>>socket message: ' + resoult);
      socketCallBack(resoult);
    }

  })

  wx.onSocketError(function (res) {
    socketOpen = false;
    console.log('WebSocket连接打开失败，请检查！' + res.data);
  })

  wx.onSocketClose(function (res) {
    socketOpen = false;
    console.log('WebSocket 已关闭！')
    socketInit();
  })
}

module.exports = {
  sendSocketMessage,
  socketInit,
  registCallBack
}